package com.cxr.flutter.flutterweatherchina.view

import android.app.Activity
import android.app.Application
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import androidx.constraintlayout.widget.ConstraintLayout
import com.example.ivy_ezviz_plugin.R
import com.ezvizuikit.open.EZUIError
import com.ezvizuikit.open.EZUIKit
import com.ezvizuikit.open.EZUIPlayer
import com.videogo.openapi.EZConstants
import com.videogo.openapi.EZOpenSDK
import com.videogo.openapi.bean.EZRecordFile
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.platform.PlatformView
import java.text.SimpleDateFormat
import java.util.*


class EzvizUIKitView(context: Context,
                     messenger: BinaryMessenger,
                     id: Int?,
                     params: Map<String, Any>?) : PlatformView, MethodCallHandler, Activity() {
    /*companion object {
        var instance: EzvizUIKitView? = null
    }*/

    var constraintLayout: ConstraintLayout? = null

    var mPlayer: EZUIPlayer? = null
    private var methodChannel: MethodChannel? = null
    var event: EventChannel.EventSink? = null

    init {
        //instance = this


        var AppKey = params?.get("AppKey") as String
        var accessToken = params?.get("accessToken") as String
        var playUrl = params?.get("playUrl") as String
        Log.d("My", AppKey)
        Log.d("My", accessToken)
        Log.d("My", playUrl)
        /**
         * 测试
         */
        var systemService: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        var inflate: View = systemService.inflate(R.layout.activity_ezviz, null)
        constraintLayout = inflate.findViewById(R.id.constraintLayout) as ConstraintLayout

        mPlayer = inflate.findViewById(R.id.player_ui) as EZUIPlayer

        //初始化EZUIKit
        EZUIKit.initWithAppKey(context.applicationContext as Application, AppKey)

        //设置授权token
        EZUIKit.setAccessToken(accessToken)

        //设置播放回调callback
        mPlayer?.setCallBack(
                object :EZUIPlayer.EZUIPlayerCallBack{
                    override fun onPlayTime(p0: Calendar?) {
                        //Log.d("My","onPlayTime")
                    }

                    override fun onPrepared() {
                        val loadView: View = mPlayer!!.getChildAt(mPlayer!!.childCount - 1)
                        (loadView as? RelativeLayout)?.visibility = View.GONE
                        Log.d("My", "onPrepared")
                    }

                    override fun onVideoSizeChange(p0: Int, p1: Int) {
                        Log.d("My", "onVideoSizeChange")
                        var mapOf = mutableMapOf(
                                "type" to "EZUIPlayerCallBack",
                                "code" to 0,
                                "msg" to "onVideoSizeChange"
                        )
                        event?.success(mapOf)
                    }

                    override fun onPlayFail(p0: EZUIError?) {
                        Log.d("My", "onPlayFail")
                        ///释放资源
                        releasePlayer()
                        var mapOf = mutableMapOf(
                                "type" to "EZUIPlayerCallBack",
                                "code" to 500,
                                "msg" to "onPlayFail"
                        )
                        event?.success(mapOf)
                    }

                    override fun onPlaySuccess() {
                        Log.d("My", "onPlaySuccess")
                        var mapOf = mutableMapOf(
                                "type" to "EZUIPlayerCallBack",
                                "code" to 0,
                                "msg" to "onPlaySuccess"
                        )
                        event?.success(mapOf)
                    }

                    override fun onPlayFinish() {
                        Log.d("My", "onPlayFinish")
                        var mapOf = mutableMapOf(
                                "type" to "EZUIPlayerCallBack",
                                "code" to 0,
                                "msg" to "onPlayFinish"
                        )
                        event?.success(mapOf)
                    }
                }
        )

        //设置播放参数
        mPlayer?.setUrl(playUrl)

        //开始播放
        mPlayer?.startPlay()
        methodChannel = MethodChannel(messenger, "ivy_ezviz_plugin_$id")
        methodChannel?.setMethodCallHandler(this)
        ///监听
        var eventChannel = EventChannel(messenger, "com.ivy.ezviz.uikit.event_$id")
        eventChannel?.setStreamHandler(
                object : EventChannel.StreamHandler {
                    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                        event=events
                    }

                    override fun onCancel(arguments: Any?) {

                    }
                }

        )
    }


    override fun getView(): ConstraintLayout? = constraintLayout
    override fun dispose() {
        mPlayer?.releasePlayer()
    }


    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (call.method == "getPlatformVersion") {
            result.success("Android ${android.os.Build.VERSION.RELEASE}")
        } else if (call.method == "ezviz.getStatus") {
            /**
             * 获取当前状态：
             * EZUIPlayer.STATUS_INIT = 0;
             * EZUIPlayer.STATUS_START = 1;
             * EZUIPlayer.STATUS_STOP = 2;
             * EZUIPlayer.STATUS_PLAY = 3;
             * EZUIPlayer.STATUS_PAUSE = 4;
             * @return
             */
            var status = getStatus()
            result.success(mapOf("status" to status))
        } else if (call.method == "ezviz.releasePlayer") {
            //释放资源
            releasePlayer()
            result.success(mapOf("releasePlayer" to "success"))
        } else if (call.method == "ezviz.startPlay") {
            //播放
            startPlay()
            result.success(mapOf("startPlay" to "success"))
        } else if (call.method == "ezviz.stopPlay") {
            //停止
            stopPlay()
            result.success(mapOf("stopPlay" to "success"))
        } else if (call.method == "ezviz.setUrl") {
            val url: String = call.argument("url")!!
            //设置播放的url
            setUrl(url)
            result.success(mapOf("setUrl" to "success"))
        } else if (call.method == "ezviz.pausePlay") {
            //暂停播放，回放专用接口
            pausePlay()
            result.success(mapOf("pausePlay" to "success"))
        } else if (call.method == "ezviz.resumePlay") {
            //恢复播放，回放专用接口
            resumePlay()
            result.success(mapOf("resumePlay" to "success"))
        } else if (call.method == "ezviz.seekPlayback") {
            val date: String = call.argument("date")!!
            //seek播放位置,回放使用
            seekPlayback(date)
            result.success(mapOf("seekPlayback" to "success"))
        } else if (call.method == "ezviz.setSurfaceSize") {
            val width: Int = call.argument("width")!!
            val height: Int = call.argument("height")!!
            //动态设置播放区域大小
            setSurfaceSize(width, height)
            result.success(mapOf("setSurfaceSize" to "success"))
        } else if (call.method == "ezviz.controlPTZ") {
            //deviceSerial: String, cameraNo: Int, commandStr: String, actionStr: String, speed: Int
            val deviceSerial: String = call.argument("deviceSerial")!!
            val cameraNo: Int = call.argument("cameraNo")!!
            val commandStr: String = call.argument("command")!!
            val actionStr: String = call.argument("action")!!
            val speed: Int = call.argument("speed")!!
            //动态设置播放区域大小
            var controlPTZ = controlPTZ(deviceSerial, cameraNo, commandStr, actionStr, speed)
            result.success(controlPTZ)
        } else if (call.method == "ezviz.captureCamera") {
            val deviceSerial: String = call.argument("deviceSerial")!!
            val cameraNo: Int = call.argument("cameraNo")!!
            //截图
            var captureCamera: String = captureCamera(deviceSerial, cameraNo)
            result.success(mapOf("setUrl" to captureCamera))
        } else {
            result.notImplemented()
        }
    }


    /**
     * 获取当前状态：
     * EZUIPlayer.STATUS_INIT = 0;
     * EZUIPlayer.STATUS_START = 1;
     * EZUIPlayer.STATUS_STOP = 2;
     * EZUIPlayer.STATUS_PLAY = 3;
     * EZUIPlayer.STATUS_PAUSE = 4;
     * @return
     */
    fun getStatus(): Int {
        var status = mPlayer!!.status
        return status
    }

    /**
     * 释放资源
     */
    fun releasePlayer() {
        mPlayer?.releasePlayer()
    }

    /**
     * 播放
     */
    fun startPlay() {
        mPlayer?.startPlay()
    }

    /**
     * 停止
     */
    fun stopPlay() {
        mPlayer?.stopPlay()
    }


    /**
     * 设置播放的url
     */
    fun setUrl(url: String) {
        mPlayer?.releasePlayer()
        mPlayer?.setUrl(url)
        mPlayer?.startPlay()
    }


    /**
     * 暂停播放，回放专用接口
     */
    fun pausePlay() {
        mPlayer?.pausePlay()
    }

    /**
     * 恢复播放，回放专用接口
     */
    fun resumePlay() {
        mPlayer?.resumePlay()
    }
    /**
     * seek播放位置,回放使用
    var  calendar
     */
    fun seekPlayback(date: String) {
        val sdf = SimpleDateFormat("yyyy-MM-dd")
        val date: Date = sdf.parse(date)
        val calendar = Calendar.getInstance()
        calendar.time = date
        mPlayer?.seekPlayback(calendar)
    }


    /**
     * 获取当前OSD时间
     * @return
     */
    fun getOSDTime(): Calendar {
        var osdTime: Calendar = mPlayer!!.getOSDTime()
        return osdTime
    }

    /**
     * 获取播放的文件列表
     * @return
     */
    fun getPlayList(): List<EZRecordFile> {
        var playList: List<EZRecordFile> = mPlayer!!.getPlayList()
        return playList
    }

    /**
     * 动态设置播放区域大小
     * 当width等于0（height等于0）时，播放区域以height（width）为标准，宽高按视频分辨率比例播放
     *
    var  width  播放区域宽
    var  height 播放区域高
     */
    fun setSurfaceSize(width: Int, height: Int) {
        mPlayer?.setSurfaceSize(width, height)
    }

    /**
     * PTZ 控制接口
     * 该接口为耗时操作，必须在线程中调用
    var  deviceSerial   设备序列号
    var  cameraNo        通道号
    var  command ptz控制命令
    var  action 控制启动/停止
    var  speed 速度（0-2）
     * @return 操作成功或者失败(返回失败错误码)
     */
    fun controlPTZ(deviceSerial: String, cameraNo: Int, commandStr: String, actionStr: String, speed: Int): Map<String, String> {

        var command: EZConstants.EZPTZCommand = EZConstants.EZPTZCommand.EZPTZCommandUp//ptz控制命令
        if (commandStr == "EZPTZCommand.EZPTZCommandUp") {
            command = EZConstants.EZPTZCommand.EZPTZCommandUp//ptz控制命令
        } else if (commandStr == "EZPTZCommand.EZPTZCommandDown") {
            command = EZConstants.EZPTZCommand.EZPTZCommandDown//ptz控制命令
        } else if (commandStr == "EZPTZCommand.EZPTZCommandLeft") {
            command = EZConstants.EZPTZCommand.EZPTZCommandLeft//ptz控制命令
        } else if (commandStr == "EZPTZCommand.EZPTZCommandRight") {
            command = EZConstants.EZPTZCommand.EZPTZCommandRight//ptz控制命令
        } else if (commandStr == "EZPTZCommand.EZPTZCommandZoomIn") {
            command = EZConstants.EZPTZCommand.EZPTZCommandZoomIn//ptz控制命令
        } else if (commandStr == "EZPTZCommand.EZPTZCommandZoomOut") {
            command = EZConstants.EZPTZCommand.EZPTZCommandZoomOut//ptz控制命令
        }
        var action: EZConstants.EZPTZAction = EZConstants.EZPTZAction.EZPTZActionSTART //控制启动/停止
        if (actionStr == "EZPTZAction.EZPTZActionSTART") {
            action = EZConstants.EZPTZAction.EZPTZActionSTART;
        } else if (actionStr == "EZPTZAction.EZPTZActionSTOP") {
            action = EZConstants.EZPTZAction.EZPTZActionSTOP;
        }
        Thread(Runnable {
            try {
                EZOpenSDK.getInstance().controlPTZ(deviceSerial, cameraNo, command, action, speed)
            } catch (e: Exception) {
                Log.d("Log", e.message.toString().replace("Resp Error:", ""))
                runOnUiThread(Runnable {
                    var mapOf = mutableMapOf(
                            "type" to "controlPTZ",
                            "code" to 500,
                            "msg" to e.message.toString()
                    )
                    event?.success(mapOf)
                    // 运行在UI线程里面的
                })

            }

        }).start()
        return mapOf("msg" to "success")

    }

    /**
     * 截图
     */
    fun captureCamera(deviceSerial: String, cameraNo: Int): String {

        var captureCamera: String = ""
        Thread(Runnable {
            try {
                captureCamera = EZOpenSDK.getInstance().captureCamera(deviceSerial, cameraNo)
                runOnUiThread(Runnable {
                    var mapOf = mutableMapOf(
                            "type" to "captureCamera",
                            "code" to 0,
                            "msg" to captureCamera
                    )
                    event?.success(mapOf)
                })

            } catch (e: Exception) {
                Log.d("Log", e.message.toString().replace("Resp Error:", ""))
                runOnUiThread(Runnable {
                    var mapOf = mutableMapOf(
                            "type" to "captureCamera",
                            "code" to 500,
                            "msg" to e.message.toString()
                    )
                    event?.success(mapOf)
                })

            }

        }).start()

        return captureCamera
    }


}
